
<template>
  <div>
      <div class="right-view-map">
        <mapContainer @init="initMap" @zoom="zoomMap" :searchPanel="false" @click="clickMap"  @pointerMove="pointerMove" />
        <div class="groug-change-view">
          <div class="groug-list">
              <div style="padding-bottom:3px;">过旺</div>
              <div class="item" style="background-color: #d19925;"> </div>
              <div class="item"></div>
              <div class="item" style="background-color: #79C29B;"> </div>
              <div class="item" style="background-color: #F76464;"> </div>
              <div style="padding-top:3px;">差</div>
          </div>
        </div>
      </div>
      <PoiPopup v-if="showPop &&currentZoom>12" :popOption="popObjct"   @onClose="(type)=>{showPop=type}" />
  </div>
</template>

<script setup>  
import { nextTick, ref, watch, onActivated,reactive,onMounted,computed} from 'vue'
import{useRouter,useRoute} from "vue-router"
import {getMinLandList} from '@/api/plant'
import {message} from '@/utils/element'
import { useUserStore } from '@/pinia/modules/user'
import  mapContainer from '@/components/Map/index.vue'
import {WktToPolygon } from '@/components/Map/utils/geoToWkt';
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer"
import Graphic from "@arcgis/core/Graphic"
import * as webMercatorUtils from "@arcgis/core/geometry/support/webMercatorUtils.js";
import PoiPopup from '@/components/Map/components/PoiPopup.vue';
import Point from '@arcgis/core/geometry/Point.js';
import {VXETable} from 'vxe-table'
const emit = defineEmits(['close','change','complete'])
const router = useRouter()
const userStore = useUserStore()
const currentZoom= ref(5)
const clickRow = ref(null)
const showPop = ref(false)
const popObjct = ref({})
const loadingCount = ref(1)
let mapView =null
let graphicsLayer = null
const props = defineProps({
  selectList: {
    type: Array,
    default: []
 },
 locationObject: {
    type: Object,
    default: {}
 },
 color: {
    type: String,
    default: '#25c289'
 }

 
})
watch(()=>props.selectList,(n,o)=>{
  changeLandColor() 
})
watch(()=>props.locationObject,(n,o)=>{
  if(mapView){
     mapView.set({center: [props.locationObject?.locationLongitude||0, props.locationObject?.locationLatitude||0]})
      let obj = graphicsLayer.graphics.items.find(item => item.attributes.type != 'text' && item.attributes.farmLandId ==props.locationObject.farmLandId)
      if(obj){
        showPop.value= true
        clickRow.value= obj.attributes
        getClickData()
      }
  }
})


//选中-地块改变颜色
const changeLandColor =()=>{
      if (graphicsLayer) {
          graphicsLayer.graphics.items.forEach((item) =>{
            if(props.selectList.includes(item.attributes.farmLandId)){
              item.symbol = {
                      type: 'simple-fill',
                      color:props.color,
                      outline: {
                          color: props.color,
                          width: 1
                      }
              }
            }else{
              item.symbol = {
                      type: 'simple-fill',
                      color:'#25c28900',
                      outline: {
                          color: '#25c289',
                          width: 1
                      }
              }
            }
          })
   }
}
const getLandData =async ()=>{
let res = await getMinLandList({
        page:1,
        limit:1,
        farmId:userStore.userInfo.farmId,
        // farmLandStatus:0,
        companyId:userStore.userInfo.companyId
     })
  if(res.success){
    getLandTimes(res.total||1)
  }else{
    message('出错了', 3)
  }
}
const getLandTimes =async (farmLandCount)=>{
    let limit=500
     let params ={
      farmId:userStore.userInfo.farmId, 
      // farmLandStatus:0,
      companyId:userStore.userInfo.companyId}
        if(farmLandCount>0){
          let pageStr = (farmLandCount/limit).toFixed(3)
          let totalPage =0
          let page1 = pageStr.split('.')[0]
          let page2 = pageStr.split('.')[1]
          let pages =[]
          if(Number(page2)>0){
            totalPage = Number(page1)+1
          }
          for(let i=1;i<=totalPage;i++){
            pages.push({page:i,limit:limit})
          }
          pages.forEach(async (item)=>{
            setTimeout(async () => {
              let res =await getMinLandList({...params,...item})
              if(res.success){
                 drawLandList(res.data||[])
              }  
            }, item.page==1?0:(item.page*1000));
      })
  }
}

const initMap = (map)=>{
     mapView = map
    getLandData()
}

const zoomMap=(val)=>{
    currentZoom.value = val
    if(graphicsLayer){
          const graphics = graphicsLayer.graphics.items.filter(item => item.attributes.type == 'text')
          graphics.forEach(item => {item.visible = val > 17 ? true : false})
    }
    getClickData()
}

const pointerMove=(val)=>{
 getClickData()
}


const clickMap =(e,e2)=>{
    if(e2.results.length>0){
        e2.results.forEach(e3 => {
        let attrs = e3.graphic.attributes
       if(attrs?.class == "click-landMark") { 
        let obj = graphicsLayer.graphics.items.find(item => item.attributes.farmLandId ==attrs.farmLandId)
          if(obj){
            showPop.value= true
            clickRow.value= obj.attributes
            getClickData()
          }
        }
      })
    }
}

//地块绘制到地图
const drawLandList = (dataList)=>{
  if(!graphicsLayer){
    graphicsLayer = new GraphicsLayer({ id:'select-land-plot'});
  }else{
    //graphicsLayer.removeAll()
  }
  dataList.forEach((item,index)=>{
    if(item?.geom){
        const geo = WktToPolygon(item.geom, { wkid: 4326 });
        const newGeo = webMercatorUtils.geographicToWebMercator(geo)
        const polygon = new Graphic({
          geometry: newGeo,
          symbol: {
            type: 'simple-fill',
            color:'#25c28900',
            outline: {
                color: '#25c289',
                width: 1
            }
          },
          attributes: {
            class: 'click-landMark',
            farmLandId:item.farmLandId,
            ...item
          }
          })
          const textAreaStyle = {
              type: "text", 
              color: [255, 255, 255],
              haloColor: [0, 0, 0],
              haloSize: "1px",
              text: "",
              xoffset: 0,
              yoffset: 0,
              cursor: 'pointer',
              font: {
                size: 10,
                family: "PingFangSC",
                weight: "bold"
              }
          }
          const AreaGeometry = polygon.geometry.extent.center
          const areaValue = Number(item.mapAreaSize.toFixed(1))
          let result = "";
          for (let i = 0, len = item.farmLandName.length; i < len; i++) {
            if (i % 8 === 0 && i != 0) result += '\n';
            result += item.farmLandName[i];
            }
          textAreaStyle.text = `${result}\n${areaValue}亩`
          const textAttr = { ...item, type: 'text' }
          const textAreaGraphic = new Graphic({
              geometry: AreaGeometry,
              symbol: textAreaStyle,
              attributes: textAttr,
              visible: currentZoom.value>17?true:false
            })
            graphicsLayer.add(polygon);
            graphicsLayer.add(textAreaGraphic)
    }
  })
  mapView.map.add(graphicsLayer)
  if(loadingCount.value==1){
    loadingCount.value = 2
    setTimeout(() => {
        mapView.goTo(graphicsLayer.graphics.items);
    }, 500);
  }
}


//点击坐标点的弹出框数据
const getClickData = ()=>{
if(!clickRow.value){return}
let item = clickRow.value
const mapPoint = new Point({longitude: item.locationLongitude,latitude: item.locationLatitude, spatialReference: {wkid: 4326}});
 const { x, y } = mapView.toScreen(mapPoint)
 item.x = x
 item.y = y
const popOption = {
          title:item.farmName||item.farmLandNo,
          farmId:item.farmId,
          companyId:item.companyId,
          farmLandId:item.farmLandId,
          pic:item.pic,
          screenX: item.x+10,
          screenY: item.y+10,
          visible:true,
          mapX: item.longitude,
          mapY: item.latitude,
          btnText:'地块详情',
          values: [
              // {
              //     label: '所属农场',
              //     value: item.farmName
              // },
              {
                  label: '地块编号',
                  value: item.farmLandNo
              },
              {
                  label: '地块名称',
                  value: item.farmLandName
              },
              {
                  label: '地块面积',
                  value:  Number(item.mapAreaSize.toFixed(1))+'亩'
              },
              {
                  label: '位置',
                  value: item.locationAddress
              }
          ],
          ...item
}
popObjct.value = popOption
}

</script>
<style>
.filter-view .el-select .el-input__inner{
  background-color: #f5f7fa;
}
</style>
<style lang="scss" scoped>
.receive-land-left-view{
      box-sizing: border-box;
      display: flex;
      flex-flow: column;
      height: 100%;
      padding: 0;
      //overflow: hidden;
      .mass-view{
          display: flex;
          justify-content: space-between;
          padding: 6px 10px;
          border-bottom: 1px solid #ddd;
          margin-bottom: 10px;
          .name{
              font-size:15px;
              font-weight: bold;
              color: #333;
              position: relative;
              &::after{
                  position: absolute;
                  contain: '';
                  content:'';
                  height:16px;
                  width:2px;
                  background-color: #04AE70;
                  left: -5px;
              }
          }
      }
    .filter-view{
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f5f7fa;
        padding:6px 0;
        .el-input__inner{
          background-color: #f5f7fa;
        }
    }
}


.right-view-map{
  height: calc(100vh - 70px);
  position: relative;
  width:100%;
  .groug-change-view{
      position: absolute;
      bottom:10px;
      left:10px;
      z-index:99; 
      width:40px;
      border:1px solid #00000080;
      .groug-list{
          background-color: #00000080;
          color: #fff;
          text-align: center;
          font-size:12px;
          padding:10px 0;
          .item{
              height:15px;
              width:10px;
              margin:0 auto;
              color: #fff;
              position: relative;
              background-color:#04AE70;
          }
      }
  }
  .groug-right-view{
      position: absolute;
      bottom:20px;
      right:80px;
      z-index:99; 
      border:1px solid #a9a8a8;
      background-color: #00000080;
      padding:12px 20px;
      font-size:15px;
      color: #fff;
      text-align: center;
      .choose-land{
          margin: 8px 0px;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
      }
  }
 .groug-view{
      position: absolute;
      bottom:10px;
      left:10px;
      z-index:99;
      .groug-list{
          background-color: #fff;
          display: flex;
          justify-content: flex-start;
          .item{
              height:36px;
              line-height:36px;
              padding:0 12px;
              font-size:14px;
              cursor: pointer;
          }.on{
              background-color: #04AE70;
              color:#fff;
          }
      }
 }
}
</style>
